<?php

namespace App\Http\Controllers\MiniAPP;

use App\Helper\ApiResponseHelper;
use App\Helper\WechatHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\MiniAPP\LoginRequest;
use App\Http\Requests\MiniAPP\MiniAuthCodeRequest;
use App\Http\Requests\MiniAPP\UserInfoRequest;
use App\Http\Resources\MiniAPP\LoginResource;
use App\Http\Resources\MiniAPP\MemberResource;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function testLogin(Request $request)
    {
        $member = Member::login($request->input('telephone'));

        return new LoginResource($member);
    }

    public function getInfo()
    {
        $member = Auth::user();

        return new LoginResource($member);
    }

    public function loginWithTelephone(LoginRequest $request, WechatHelper $wechatHelper)
    {
        $app = $wechatHelper->getMiniApp();

        $res = $app->phone_number->getUserPhoneNumber($request->input('code'));

        if ($res['errcode'] != 0)
            return ApiResponseHelper::json([], 400, '获取手机号失败，请重试');

        $telephone = $res['phone_info']['purePhoneNumber'];

        $member = Member::login($telephone);

        return new LoginResource($member);
    }

    public function updateInfo(UserInfoRequest $request)
    {
        $member = Auth::user();
        $member->update($request->only([
            'name', 'avatar'
        ]));

        return new MemberResource($member);
    }

    public function miniAppCode2Openid(MiniAuthCodeRequest $request, WechatHelper $helper)
    {
        $app = $helper->getMiniApp();
        $res = $app->auth->session($request->input('code'));

        if (isset($res['errcode']) && $res['errcode'] != 0)
            return ApiResponseHelper::json([], 400, $res['errmsg']);

        return ApiResponseHelper::json([
            'openid' => $res['openid'],
//            'unionid' => $res['unionid']
        ]);
    }
}
